package net.zhengxinyun.performance.service.incentive;

import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.api.entity.SysFile;
import net.zhengxinyun.performance.api.mapper.SysFileMapper;
import net.zhengxinyun.performance.entity.IncentiveEntity;
import net.zhengxinyun.performance.filter.IncentiveFilter;
import net.zhengxinyun.performance.filter.IndexFilter;
import net.zhengxinyun.performance.mapper.incentive.IncentiveEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * @Auther: hyp
 * @Date: 2018/11/4 15:11
 */
@Service
public class IncentiveServiceImpl implements IncentiveService {

    private IncentiveEntityMapper incentiveEntityMapper;
    private SysFileMapper sysFileMapper;

    @Autowired
    public IncentiveServiceImpl(IncentiveEntityMapper incentiveEntityMapper, SysFileMapper sysFileMapper) {
        this.incentiveEntityMapper = incentiveEntityMapper;
        this.sysFileMapper = sysFileMapper;
    }

    @Override
    @Transactional
    public String delete(IncentiveEntity incentiveEntity) {
        IncentiveEntity entity = incentiveEntityMapper.selectByPrimaryKey(incentiveEntity.getId());
        String[] str = entity.getFileId().split(",");
        for (int i = 0;i<str.length;i++){
            String id = str[i];
            int temp = sysFileMapper.deleteByPrimaryKey(Long.valueOf(id));
            if (temp == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "证明材料删除失败";
            }
        }
        int a =incentiveEntityMapper.deleteByPrimaryKey(incentiveEntity.getId());
        if (a == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "正向激励事项删除失败";
        }
        return "删除成功";
    }

    @Override
    @Transactional
    public String update(IncentiveEntity incentiveEntity) {
        int i =incentiveEntityMapper.updateByPrimaryKey(incentiveEntity);
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "修改失败";
        }
        return "修改成功";
    }

    @Override
    @Transactional
    public String insert(IncentiveEntity incentiveEntity) {
        incentiveEntity.setAudit("0");
        if (StringUtils.isBlank(incentiveEntity.getFileId())){
            return "上传材料不能为空";
        }
        int i = incentiveEntityMapper.insert(incentiveEntity);
        if (i == 0 ){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "添加失败,请联系管理员";
        }
        return "添加成功";
    }

    @Override
    public List<Map<String,Object>> query(IncentiveFilter incentiveFilter) {
        List<Map<String,Object>> list = new ArrayList<>();
        List<IncentiveFilter> incentiveList = incentiveEntityMapper.query(incentiveFilter);
        for (IncentiveFilter filter:incentiveList) {
            Map<String,Object> map = new HashMap<>();
            List<Map<String,Object>> fileList = new ArrayList<>();
            String[] str = filter.getFileId().split(",");
                for (int i = 0; i < str.length; i++) {
                    Map<String,Object> fileMap = new HashMap<>();
                    String id = str[i];
                    if (Util.isNumber(id)){
                        SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(id));
                        if (sysFile == null){
                            continue;
                        }
                        fileMap.put("id",sysFile.getId());
                        fileMap.put("url",sysFile.getUrl());
                        fileMap.put("status","finished");
                        fileList.add(fileMap);
                    }
                }
            filter.setFileList(fileList);
            map.put("incentive",filter);
            list.add(map);
        }
        return list;
    }

    public  int queryForCount(IncentiveFilter filter){
        return incentiveEntityMapper.queryForCount(filter);
    }

    /**
     * 加分类别占比
     * @return
     */
    public List<IncentiveFilter> queryGroupType(String dateTime){
        List<IncentiveFilter> list = incentiveEntityMapper.queryGroupType(dateTime);
        if (list == null || list.size() == 0){
            for (int i = 1;i <= 5;i++){
                IncentiveFilter filter = new IncentiveFilter();
                filter.setPointsType(String.valueOf(i));
                filter.setPoint("0");
                list.add(filter);
            }
            return list;
        }
        double total = (double)incentiveEntityMapper.queryForCount(new IncentiveFilter());
        for (IncentiveFilter filter:list) {
            if(StringUtils.isNotBlank(filter.getNum())){
                filter.setPoint(Util.doubleFormat(Double.parseDouble(filter.getNum())/total*100));
            }else {
                filter.setPoint("0");
            }
        }
        return list;
    }

    /**
     * 个月加分项目数量
     * @return
     */
    public List<IncentiveFilter> queryGroupMonth(String dateTime){
        List<IncentiveFilter> list = incentiveEntityMapper.queryGroupMonth(dateTime);
        String totalSB = "01,02,03,04,05,06,07,08,09,10,11,12";
        String spit = ",";
        for (IncentiveFilter filter:list) {
           totalSB = totalSB.replace(filter.getMonthTime(),"");
        }
        String[] str = totalSB.split(spit);
        for (int i = 0;i < str.length;i++){
            if (StringUtils.isBlank(str[i])){
                continue;
            }
            IncentiveFilter incent = new IncentiveFilter();
            incent.setMonthTime(str[i]);
            incent.setNum("0");
            list.add(incent);
        }
        Collections.sort(list, new Comparator<IncentiveFilter>() {
            @Override
            public int compare(IncentiveFilter o1, IncentiveFilter o2) {
                if (Integer.parseInt(o1.getMonthTime()) > Integer.parseInt(o2.getMonthTime())){
                    return 1;
                }else {
                    return -1;
                }
            }
        });
        return list;
    }

    @Override
    public String pass(IncentiveEntity incentiveEntity) {
        IncentiveEntity entity = incentiveEntityMapper.selectByPrimaryKey(incentiveEntity.getId());
        entity.setAudit("1");
        String month = DateUtils.getMonth();
        entity.setMonthTime(month);
        int i = incentiveEntityMapper.updateByPrimaryKeySelective(entity);
        if (i == 0){
            return "审核失败,请重试";
        }
        return "审核成功";
    }

    @Override
    public String noPass(IncentiveEntity incentiveEntity) {
        IncentiveEntity entity = incentiveEntityMapper.selectByPrimaryKey(incentiveEntity.getId());
        entity.setAudit("2");
        entity.setReason(incentiveEntity.getReason());
        int i = incentiveEntityMapper.updateByPrimaryKeySelective(entity);
        if (i == 0){
            return "回退失败,请重试";
        }
        return "回退成功";
    }

    @Override
    public List<Map<String,Object>> queryForAudit(IncentiveFilter incentiveFilter) {
        List<Map<String,Object>> list = new ArrayList<>();
        List<IncentiveFilter> incentiveList = incentiveEntityMapper.queryForAudit(incentiveFilter);
        for (IncentiveFilter filter:incentiveList) {
            Map<String,Object> map = new HashMap<>();
            List<Map<String,Object>> fileList = new ArrayList<>();
            String[] str = filter.getFileId().split(",");
            for (int i = 0; i < str.length; i++) {
                Map<String,Object> fileMap = new HashMap<>();
                String id = str[i];
                if (Util.isNumber(id)){
                    SysFile sysFile = sysFileMapper.selectByPrimaryKey(Long.valueOf(id));
                    if (sysFile == null){
                        continue;
                    }
                    fileMap.put("id",sysFile.getId());
                    fileMap.put("url",sysFile.getUrl());
                    fileMap.put("status","finished");
                    fileList.add(fileMap);
                }
            }
            filter.setFileList(fileList);
            map.put("incentive",filter);
            list.add(map);
        }
        return list;
    }

    @Override
    public int queryForAuditCount(IncentiveFilter filter) {
        return incentiveEntityMapper.queryForAuditCount(filter);
    }

    @Override
    /**
     * 首页图表
     */
    public HashMap<String,Object> indexIncentive(IndexFilter indexFilter) {
        HashMap<String,Object> map = new HashMap<>();
        if (StringUtils.isBlank(indexFilter.getDateTime())){
            String dateTime = incentiveEntityMapper.queryForNewTime();
            indexFilter.setDateTime(dateTime);
            List<IncentiveFilter> list = incentiveEntityMapper.indexIncentive(indexFilter);
            Integer num = incentiveEntityMapper.indexForCount(indexFilter);
            Double totalPoint = incentiveEntityMapper.indexForScore(indexFilter);

            String totalSB = "01,02,03,04,05,06,07,08,09,10,11,12";
            String spit = ",";
            for (IncentiveFilter filter:list) {
                totalSB = totalSB.replace(filter.getMonthTime(),"");
            }
            String[] str = totalSB.split(spit);
            for (int i = 0;i < str.length;i++){
                if (StringUtils.isBlank(str[i])){
                    continue;
                }
                IncentiveFilter incent = new IncentiveFilter();
                incent.setMonthTime(str[i]);
                incent.setPoint("0");
                list.add(incent);
            }
            Collections.sort(list, new Comparator<IncentiveFilter>() {
                @Override
                public int compare(IncentiveFilter o1, IncentiveFilter o2) {
                    if (Integer.parseInt(o1.getMonthTime()) > Integer.parseInt(o2.getMonthTime())){
                        return 1;
                    }else {
                        return -1;
                    }
                }
            });

            map.put("point",totalPoint);
            map.put("num",num);
            map.put("list",list);
            return map;
        }else {
            List<IncentiveFilter> list = incentiveEntityMapper.indexIncentive(indexFilter);
            Integer num = incentiveEntityMapper.indexForCount(indexFilter);
            Double totalPoint = incentiveEntityMapper.indexForScore(indexFilter);

            String totalSB = "01,02,03,04,05,06,07,08,09,10,11,12";
            String spit = ",";
            for (IncentiveFilter filter:list) {
                totalSB = totalSB.replace(filter.getMonthTime(),"");
            }
            String[] str = totalSB.split(spit);
            for (int i = 0;i < str.length;i++){
                if (StringUtils.isBlank(str[i])){
                    continue;
                }
                IncentiveFilter incent = new IncentiveFilter();
                incent.setMonthTime(str[i]);
                incent.setPoint("0");
                list.add(incent);
            }
            Collections.sort(list, new Comparator<IncentiveFilter>() {
                @Override
                public int compare(IncentiveFilter o1, IncentiveFilter o2) {
                    if (Integer.parseInt(o1.getMonthTime()) > Integer.parseInt(o2.getMonthTime())){
                        return 1;
                    }else {
                        return -1;
                    }
                }
            });

            map.put("point",totalPoint);
            map.put("num",num);
            map.put("list",list);
            return map;
        }
    }

    @Override
    public Double indexForScore(IndexFilter indexFilter) {
        String dateTime = incentiveEntityMapper.queryForNewTime();
        if (StringUtils.isBlank(dateTime)){
            return 0.0;
        }
        indexFilter.setDateTime(dateTime);
        Double sum = incentiveEntityMapper.indexForScore(indexFilter);
        return sum;
    }


}
